package com.phuc.game.tankshooter.sprite;

import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.modifier.ParallelEntityModifier;
import org.anddev.andengine.entity.modifier.PathModifier;
import org.anddev.andengine.entity.modifier.PathModifier.Path;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.util.constants.TimeConstants;

import android.util.Log;

import com.phuc.game.tankshooter.MainActivity;
import com.phuc.game.tankshooter.engine.GamePlay;

public class BulletCountSprite extends AnimatedSprite implements TimeConstants {

	private static final int FULL_SIZE = 150;
	private static final float RESTORE_DURATION = 2.5f;
	float alpha;
	float scale;

	public BulletCountSprite() {
		super(3, 25, 32, FULL_SIZE,
				GamePlay.textureBulletNum.getFaceTiledTextureRegion());
	}
	
	PathModifier pm;
	float heightStartRestore = FULL_SIZE;
	
	public void reloading() {
		final GamePlay game = MainActivity.getInstant().getGamePlay();
		heightStartRestore = this.getHeight();
		float durationRestore = RESTORE_DURATION * (FULL_SIZE - heightStartRestore) / FULL_SIZE;
		Log.d("phucphuc", "phucphuc pSecondsElapsed duration = "  + 
				durationRestore);
		Path path = new Path(2).to(this.getX(), this.getY()).to(this.getX(), 25);
		
		pm = new PathModifier(durationRestore, path,
				new PathModifier.IPathModifierListener() {
			@Override
			public void onPathStarted(PathModifier pPathModifier,
					IEntity pEntity) { }

			@Override
			public void onPathWaypointStarted(PathModifier pPathModifier,
					IEntity pEntity, int pWaypointIndex) { }

			@Override
			public void onPathWaypointFinished(PathModifier pPathModifier,
					IEntity pEntity, int pWaypointIndex) { }

			@Override
			public void onPathFinished(PathModifier pPathModifier,
					IEntity pEntity) {
				game.restoreRocketNum();
				MainActivity.getInstant().isReloading = false;
				MainActivity.getInstant().showReloadDialog(false);
			}
		});

		ParallelEntityModifier modifier = new ParallelEntityModifier(pm);
		this.registerEntityModifier(modifier);
	}
	
	@Override
	public void onManagedUpdate(final float pSecondsElapsed) {
		super.onManagedUpdate(pSecondsElapsed);
		GamePlay game = MainActivity.getInstant().getGamePlay();
		
		if (MainActivity.getInstant().isReloading) {
			float rate = pm.getSecondsElapsed() / (float)RESTORE_DURATION;
			this.setHeight(rate * FULL_SIZE + heightStartRestore);
			Log.d("phucphuc", "phucphuc pSecondsElapsed = "  + 
					rate);
		} else {
			int height = FULL_SIZE * game.getRocketNum() / game.getRocketNumTotal();
			this.setHeight(height);
			this.setPosition(this.getX(), FULL_SIZE - height + 25);

			if (game.getRocketNum() <= 0) {
				MainActivity.getInstant().isReloading = true;
				MainActivity.getInstant().showReloadDialog(true);
				reloading();
			}
		}
	}
}
